#include <sstream>

#ifdef SYPX_MEMCHECK
#include "mmgr.h"
#endif

#include "TextBox.h"
#include "Font.h"
#include "Engine.h"
#include "Renderer.h"
#include "Mesh.h"

namespace SypX
{
	TextBox::TextBox(Font* f , float width, float height, UByte horizontalPad, UByte verticalPad):GuiComponent(width, height),font(f), horPad(horizontalPad), verPad(verticalPad), bgColor(0.0f,0.0f,0.0f,1.0f), borderColor(0.5f,0.5f,0.5f,1.0f), textColor(1.0f,1.0f,1.0f,1.0f)
	{
		initAsQuad(width, height);

		border = new Mesh();
		border->setPrimitiveType(LINELOOP);
		border->setStride(0);
		std::ostringstream oss;
		oss<<"TextBox_Border"<<getUniqueID();
		border->setFileName(oss.str());

		FloatArray& data = border->getDataArrayRef();
		float hw = width/2.0f;
		float hh = height/2.0f;

		data.push_back(-hw);
		data.push_back(-hh);
		data.push_back(0.1f);	//draw above the background

		data.push_back(hw);
		data.push_back(-hh);
		data.push_back(0.1f);

		data.push_back(hw);
		data.push_back(hh);
		data.push_back(0.1f);

		data.push_back(-hw);
		data.push_back(hh);
		data.push_back(0.1f);

		borderInstance = new MeshInstance();
		borderInstance->setPosition(Vec3(0,0,0.01f));	//Slightly infront of background
		borderInstance->useMesh(border);
		borderInstance->setParent(mi);

	}

	TextBox::~TextBox(void)
	{
		delete borderInstance;

	}

	void TextBox::draw()
	{
		Renderer* render = Engine::getSingleton()->getRenderer();

		render->setActiveColor(bgColor);
		render->drawMesh(mi);

		render->setActiveColor(borderColor);
		render->drawMesh(borderInstance);

		render->setActiveColor(textColor);
		font->drawText(text, mi->getPositionRef().x - width/2.0f + horPad, mi->getPositionRef().y + height/2.0f - font->getFontSizeY() - verPad, mi->getPositionRef().z + 0.01f);
		font->drawBufferedInstances();
	}

	void TextBox::setText(const String& txt)
	{
		text = font->wordWrap(txt, width);

	}

	void TextBox::setBorderColor(const Vec4& color)
	{
		borderColor = color;
	}

	void TextBox::setTextColor(const Vec4& color)
	{
		textColor = color;
	}

	void TextBox::setBgColor(const Vec4& color)
	{
		bgColor = color;
	}
}
